package org.opensourceway.sbom.service.vul.impl;

import org.opensourceway.sbom.api.vul.MajunVulClient;
import org.opensourceway.sbom.dao.VulnerabilityLifecycleRepository;
import org.opensourceway.sbom.model.entity.VulnerabilityLifecycle;
import org.opensourceway.sbom.model.pojo.response.vul.uvp.IssueDetail;
import org.opensourceway.sbom.model.pojo.response.vul.uvp.MajunVulDetailsResponse;
import org.opensourceway.sbom.service.vul.MajunVulService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;



@Service
public class MajunVulServiceImpl implements MajunVulService {

    @Autowired
    private MajunVulClient majunVulClient;

    @Autowired
    private VulnerabilityLifecycleRepository vulnerabilityLifecycleRepository;
    @Override
    public void syncMajunVulData() {

        Mono<MajunVulDetailsResponse> majunVulDetailsResponseMono = majunVulClient.getMajunVulDetails();

        List<IssueDetail> details = new ArrayList<>();
        majunVulDetailsResponseMono.doOnNext(majunVulDetailsResponse -> {
            System.out.println(majunVulDetailsResponse.getCode());
            System.out.println(majunVulDetailsResponse.getMessage());
            details.addAll(majunVulDetailsResponse.getResult());
        }).block();

        List<VulnerabilityLifecycle> vulnerabilityLifecycles = details.stream()
                .map(detail -> {
                    VulnerabilityLifecycle vulnerabilityLifecycle = new VulnerabilityLifecycle();
                    vulnerabilityLifecycle.setIssueId(detail.getIssueId());
                    vulnerabilityLifecycle.setIssueCustomizeState(detail.getIssueCustomizeState());
                    vulnerabilityLifecycle.setAffectedSoftware(detail.getAffectedSoftware());
                    vulnerabilityLifecycle.setUnAffectedBranches(detail.getUnAffectedBranches());
                    vulnerabilityLifecycle.setAffectedBranches(detail.getAffectedBranches());
                    vulnerabilityLifecycle.setNotAnalyzedBranches(detail.getNotAnalyzedBranches());
                    vulnerabilityLifecycle.setCveNum(detail.getCveNum());
                    String versions = (detail.getVersions() != null) ? detail.getVersions().toString() : null;
                    vulnerabilityLifecycle.setVersions(versions);
                    return vulnerabilityLifecycle;
                })
                .toList();
        vulnerabilityLifecycleRepository.saveAll(vulnerabilityLifecycles);

    }
}
